<template>
  <div class="" v-if="state !== 'hidden'">

    <el-form ref="form" :model="form" :label-width="'write' == state ? '115px':'auto'"
             :class="'write' == state ? 'write-form':'read-form'"
             :label-position="'write' == state ? 'top':'left'">
      <div class="card-wrap flex-column justify-end card-padding">
        <div class="card-title-wrap">
          <span>司机信息</span>
          <span></span>
        </div>

        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item label="司机姓名:" prop="driverName"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入司机姓名',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, form.driverName, callback)
                                       }:{}">
              <el-input maxlength="50" v-if="'write' == state" v-model="form.driverName"
                        placeholder="请输入司机姓名"></el-input>
              <span v-else>{{ form.driverName|filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话:" prop="driverPhone"
                          :rules="'write' == state ? [{
                                         required: true,
                                         message: '请输入联系电话',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, form.driverPhone, callback)
                                       },{ pattern: /^(1[3456789]\d{9}|[0-9]{5,12})$/, message: '手机号码格式不正确', trigger: 'blur' }]:{}">
              <el-input maxlength="12" @input="value=>form.driverPhone=value.replace(/[^\d]/g,'')"
                        v-if="'write' == state" v-model="form.driverPhone" placeholder="请输入联系电话"></el-input>
              <span v-else>{{ form.driverPhone|filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="劳务公司:" prop="laborCompanyId"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择劳务公司',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.laborCompanyId, callback)
                                       }:{}">
              <el-select @change="laborChange" v-if="'write' == state" v-model="form.laborCompanyId" filterable
                         clearable style="width: 100%">
                <template v-for="dict in companyList">
                  <el-option :label="dict.companyName" :value="dict.companyId"
                             :key="dict.companyId"></el-option>
                </template>
              </el-select>
              <span v-else>{{ form.laborCompanyName|filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="城市:" prop="cityName"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择城市',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.cityName, callback)
                                       }:{}">
              <ProvinceCity v-if="'write' == state" v-model="form.citydata"
                            placeholder="请选择城市" ref="citySelect"
                            :showAllLevels="false"
                            @change="citySelectionChange"></ProvinceCity>
              <span v-else>{{ form.cityName|filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属公司:" prop="belongCompanyId"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择所属公司',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.belongCompanyId, callback)
                                       }:{}">
              <el-select @change="belongChange" v-if="'write' == state" v-model="form.belongCompanyId" filterable
                         clearable style="width: 100%">
                <template v-for="(item, index) in belongCompanyList">
                  <el-option :label="item.deptName" :value="item.deptId" :key="index"></el-option>
                </template>
              </el-select>

              <span v-else>{{ form.belongCompanyName|filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="驾照发放日:" prop="driverLicenseDate"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择驾照发放日',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.driverLicenseDate, callback)
                                       }:{}">
              <el-date-picker v-if="'write' == state"
                              v-model="form.driverLicenseDate"
                              type="date"
                              align="left"
                              unlink-panels
                              placeholder="请选择"
                              value-format="yyyy-MM-dd"
                              format="yyyy-MM-dd">
              </el-date-picker>
              <span v-else>{{ form.driverLicenseDate|filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="驾照种类:" prop="driverLicenseType"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入驾照种类',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, form.driverLicenseType, callback)
                                       }:{}">
              <el-input maxlength="50" v-if="'write' == state" v-model="form.driverLicenseType"
                        placeholder="请输入驾照种类"></el-input>
              <span v-else>{{ form.driverLicenseType|filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="驾照号码:" prop="driverLicenseNo"
                          :rules="'write' == state ? [{
                                         required: true,
                                         message: '请输入驾照号码',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, form.driverLicenseNo, callback)
                                       }, { pattern:/(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/, message: '请输入正确的证件号码', trigger: 'blur' }]:{}">
              <el-input @input="value=>form.driverLicenseNo=value.replace(/[^\w_]/g, '')" maxlength="19"
                        v-if="'write' == state" v-model="form.driverLicenseNo" placeholder="请输入驾照号码"></el-input>
              <span v-else>{{ form.driverLicenseNo|filterNull }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="nc供应商id:" prop="ncSupplierId">
              <el-input maxlength="50" v-if="'write' == state" v-model="form.ncSupplierId"
                        placeholder="请输入nc供应商id"></el-input>
              <span v-else>{{ form.ncSupplierId|filterNull }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="nc供应商code:" prop="ncSupplierCode">
              <el-input maxlength="50" v-if="'write' == state" v-model="form.ncSupplierCode"
                        placeholder="请输入nc供应商code"></el-input>
              <span v-else>{{ form.ncSupplierCode|filterNull }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <div style="padding-bottom: 18px">账户信息</div>
            <el-table border :data="form.driverBankAccounts" :header-cell-class-name="headerClass" style="width: 100%">
              <el-table-column type="index" key="index" width="50" align="center" label="序号"/>

              <el-table-column prop="accountName" key="accountName" align="center" min-width="170" label="开户名称">
                <template #default="{row,$index}">
                  <el-form-item label-width="0" :prop="`driverBankAccounts.${$index}.accountName`"
                                style="width: 100%"
                                :rules="{
                                  required: 'write' == state ,
                                  message: '请输入开户名称',
                                  trigger: 'blur',
                                  validator: (rule, value, callback) => validData(rule, row.accountName, callback)
                                }">
                    <el-input v-if="'write' == state" maxlength="50" v-model="row.accountName" clearable
                              placeholder="请输入开户名称"/>
                    <span v-else>{{ row.accountName|filterNull }}</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="bankName" key="bankName" align="center" min-width="170" label="开户银行">
                <template #default="{row,$index}">
                  <el-form-item label-width="0" :prop="`driverBankAccounts.${$index}.bankName`" style="width: 100%"
                                :rules="{
                                required: 'write' == state,
                                message: '请选择开户银行',
                                trigger: 'change',
                                validator: (rule, value, callback) => validData(rule, row.bankName, callback)
                                }">
                    <el-input
                        v-if="'write' == state"
                        @focus="select_dialog(row,$index)"
                        v-model="row.bankName"
                        ref="selectDialogInput"
                        clearable
                        @clear="clear(row)"
                        placeholder="请选择开户银行"/>
                    <span v-else>{{ row.bankName|filterNull }}</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="accountNumber" key="accountNumber" align="center" min-width="170" label="银行账户">
                <template #default="{row,$index}">
                  <el-form-item label-width="0" :prop="`driverBankAccounts.${$index}.accountNumber`" style="width: 100%"
                                :rules="{
                                required: 'write' == state,
                                message: '请输入银行账户',
                                trigger: 'blur',
                                 validator: (rule, value, callback) => validData(rule, row.accountNumber, callback)
                                }">
                    <el-input v-if="'write' == state" maxlength="30"
                              @input="value=>row.accountNumber=value.replace(/[^\d]/g,'')"
                              v-model="row.accountNumber" clearable placeholder="请输入银行账户"/>
                    <span v-else>{{ row.accountNumber|filterNull }}</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column prop="accountStatus" key="accountStatus" align="center" width="125"
                               label="是否为生效账号">
                <template #default="{row}">
                  <el-switch v-if="'write' == state" active-value="0" inactive-value="1"
                             v-model="row.accountStatus">
                  </el-switch>
                  <span v-else>{{ 0 == row.accountStatus ? '是' : 1 == row.accountStatus ? '否' : '--' }}</span>
                </template>
              </el-table-column>

              <el-table-column v-if="'write' == state" label="操作" width="80" align="center"
                               class-name="small-padding fixed-width">
                <template #default="{row,$index}">
                  <e-button size="mini" type="text" icon="el-icon-delete"
                            @click="handleDelete(row, $index)">删除
                  </e-button>
                </template>
              </el-table-column>

              <template v-slot:append v-if="'write' == state">
                <div class="flex-xy-center" style="height: 40px">
                  <e-button type="text" icon="eel-icon-plus"
                            @click="addAccount">新增
                  </e-button>
                </div>
              </template>


            </el-table>
          </el-col>

          <el-col :span="24">
            <el-form-item label="上传身份证:" prop="identityFrontImg"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请上传身份证',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.identityFrontImg, callback)
                                       }:{}">
              <div class="flex">
                <ImageCommon :disabled="'write' != state" info="身份证正面" :limit="1"
                             v-model="form.identityFrontImg"></ImageCommon>
                <ImageCommon :disabled="'write' != state" info="身份证反面" :limit="1"
                             v-model="form.identityBackImg"></ImageCommon>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传驾驶证:" prop="driverLicenseFrontImg"
                          :rules="'write' == state ? {
                                         required: true,
                                         message: '请上传驾驶证',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.driverLicenseFrontImg, callback)
                                       }:{}">
              <div class="flex">
                <ImageCommon :disabled="'write' != state" info="驾驶证正面" :limit="1"
                             v-model="form.driverLicenseFrontImg"></ImageCommon>
                <ImageCommon :disabled="'write' != state" info="驾驶证反面" :limit="1"
                             v-model="form.driverLicenseBackImg"></ImageCommon>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input maxlength="500" type="textarea" v-if="'write' == state" v-model="form.remark"
                        placeholder="请输入备注"></el-input>
              <span v-else>{{ form.remark|filterNull }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="1==form.delStatus">
            <el-form-item label="删除备注:" prop="delRemark">
              <el-input type="textarea" v-if="'write' == state" v-model="form.delRemark" maxlength="500"
                        placeholder="请填写删除备注"></el-input>
              <span v-else>{{ form.delRemark|filterNull }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

    </el-form>

  </div>
</template>

<script>


import moment from "moment";
import ProvinceCity from "@/views/components/provinceCity/index.vue";
import {listDept} from "@/api/system/dept";
import {driverCompanySelect} from "@/api/memberManage/driverList";

export default {
  components: {ProvinceCity},
  dicts: [],
  props: {
    value: {
      default: {},
    },
    state: {
      default: "write",
    },
  },
  computed: {
    form: {
      get() {
        console.log('this.value', this.value, this.state)
        return this.value;
      },
      set(value) {
        this.$emit("input", value);
      },
    },

  },
  watch: {
    form: {
      immediate: true,
      deep: true,
      handler: function (val) {
        if (this.first && val.cityId && val.cityId != null) {
          this.first = false
          this.form.citydata = []
          //下标0为一级菜单value
          this.form.citydata[0] = this.form.provinceId;
          //下标1为二级菜单value
          this.form.citydata[1] = this.form.cityId;
          this.$forceUpdate()
        }
      }
    }
  },
  data() {
    return {
      companyList: [],
      belongCompanyList: [],
      first: true,
      //账户信息 * 标识
      headerList: ['accountName', 'bankName', 'accountNumber']
    };
  },
  mounted() {
    this.getCompanyList()
    this.getBelongCompany();
  },
  methods: {
    headerClass({row, column, rowIndex, columnIndex}) {
      for (let i = 0; i < row.length; i++) {
        if (this.headerList.includes(row[i].property) && i == columnIndex) {
          return "header-class";
        }
      }
    },

    //新增
    addAccount() {
      this.form.driverBankAccounts.push({
        bankName: null,
        bankCode:null,
        accountName: null,
        accountNumber: null,
        accountStatus: '0',
      })
      this.$forceUpdate()
    },
    //删除
    handleDelete(row, index) {
      this.form.driverBankAccounts.splice(index, 1)
    },

    //开户银行事件
    select_dialog(row, index) {
      this.$refs.selectDialogInput.blur();
      const SelectDialog =
          require('../../../../components/A/A-form/template/index').default;

      SelectDialog({type: 'bank'})
          .then(({data, type}) => {
            const exists = this.form.driverBankAccounts.some((item, ind) => item.bankCode === data.bankCode && index !== ind);
            if (exists) {
              this.$message({
                type: 'warning',
                message: '开户银行已存在'
              })
              row.bankName = '';
              row.bankCode = '';
            } else {
              row.bankName = data.bankName;
              row.bankCode = data.bankCode;
            }
          })
          .catch(err => {
          });
    },

    clear(row) {
      row.bankName = undefined;
      row.bankCode = undefined;
    },

    laborChange(val) {
      let find = this.companyList.find(item => item.companyId == val);
      if (find) {
        this.form.laborCompanyName = find.companyName
      } else {
        this.form.laborCompanyName = null
      }
    },
    belongChange(val) {
      let find = this.belongCompanyList.find(item => item.deptId == val);
      if (find) {
        this.form.belongCompanyName = find.deptName
      } else {
        this.form.belongCompanyName = null
      }
    },
    // renewSel(val){
    //     if(this.form.renewYear && this.form.renewStartTime){
    //         let endtime = moment(this.form.renewStartTime, 'YYYY-MM-DD HH:mm:ss').add(this.form.renewYear, 'year').format('YYYY-MM-DD HH:mm:ss')
    //         this.$set(this.form, 'renewEndTime', endtime)
    //     }
    //     this.$forceUpdate()
    // },
    // startChange(val){
    //     if(this.form.renewYear && this.form.renewStartTime){
    //         let endtime = moment(this.form.renewStartTime, 'YYYY-MM-DD HH:mm:ss').add(this.form.renewYear, 'year').format('YYYY-MM-DD HH:mm:ss')
    //         this.$set(this.form, 'renewEndTime', endtime)
    //     }
    //     this.$forceUpdate()
    // },

    getBelongCompany() {
      listDept(
          {
            deptType: '2',//组织类型（1组织 2公司）
            regionId: this.form.cityId,//所在城市（省市区id）
          }).then(res => {
        this.belongCompanyList = res.data
      })
    },

    laberChange(val) {
      let find = this.companyList.find(item => val == item.companyId);
      if (find) {
        this.form.laborCompanyName = find.companyName
      } else {
        this.form.laborCompanyName = null
      }
    },
    citySelectionChange(val) {
      if (val.length > 0) {
        const nodes = Array.from(val, item => ({
          value: item.value,
          label: item.label,
          pv: item.parent.value,
          pl: item.parent.label
        }))
        this.form.provinceId = nodes[0].pv
        this.form.provinceName = nodes[0].pl
        this.form.cityId = nodes[0].value
        this.form.cityName = nodes[0].label
      } else {
        this.form.provinceId = null
        this.form.provinceName = null
        this.form.cityId = null
        this.form.cityName = null
      }

      this.belongCompanyList = []
      this.getBelongCompany();
    },
    getCompanyList() {
      driverCompanySelect({
        approvalStatus: 2
      }).then(res => {
        this.companyList = res
      })

    },

    validData(rule, value, callback) {
      // console.log('aaa', rule, value, callback)
      if (rule.required && !value) {
        // this.$modal.msgError(`未填写${value}`);
        callback(new Error(rule.message));
      } else {
        callback();
      }
    },


    async valid() {
      // this.form.workId = this.form.id
      return new Promise((resolve) => {
        if ('write' == this.state) {
          this.$refs["form"].validate(valid => {
            resolve(valid);
          });
        } else {
          resolve(true)
        }

      })
    },
  }
};
</script>


<style lang="scss" scoped>
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

::v-deep .read-form .el-form-item__label-wrap,
::v-deep .read-form .el-form-item__content {
  margin-left: 0 !important;
}

.el-descriptions {
  margin: 0 -15px;
}

::v-deep .header-class {
  .cell::before {
    content: "*";
    color: red;
    padding-right: 2px;
    font-size: 14px;
  }
}
</style>
